package com.qyhl.question.question.rank;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioGroup;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.question.R;
import com.qyhl.question.R2;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.commonlib.entity.question.QuestionRankBean;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;

public class QuestionRankFragment extends BaseFragment implements QuestionRankContract.QuestionRankView {
    @BindView(R2.id.sort_rg)
    RadioGroup sortRg;
    @BindView(R2.id.recycle_view)
    RecyclerView recycleView;
    @BindView(R2.id.refresh)
    SmartRefreshLayout refresh;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;

    private String subjectId;

    private String range;

    private QuestionRankPresenter mPresenter;

    private List<QuestionRankBean> mDataList = new ArrayList<>();

    private CommonAdapter<QuestionRankBean> commonAdapter;

    private String lastPhoneNum = "";

    private String sort = "correctNum";

    private int lastCorrectNum = 0;

    private int lastTimes = 0;

    public void setRange(String range) {
        this.range = range;
    }

    public void setSubjectId(String subjectId) {
        this.subjectId = subjectId;
    }

    public static QuestionRankFragment newInstance(String subjectId, String range) {
        QuestionRankFragment fragment = new QuestionRankFragment();
        fragment.setSubjectId(subjectId);
        fragment.setRange(range);
        return fragment;
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.question_fragment_rank, null);
    }

    @Override
    protected void create() {
        loadMask.setStatus(LoadingLayout.Loading);
        mPresenter = new QuestionRankPresenter(this);

        refresh.setRefreshHeader(new MaterialHeader(getContext()));
        refresh.setRefreshFooter(new ClassicsFooter(getContext()));
        refresh.setEnableLoadMore(true);

        recycleView.setLayoutManager(new LinearLayoutManager(getContext()));
        DividerItemDecoration divider = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(Objects.requireNonNull(ContextCompat.getDrawable(getContext(), R.drawable.item_news_divider)));
        recycleView.addItemDecoration(divider);
        recycleView.setAdapter(commonAdapter = new CommonAdapter<QuestionRankBean>(getContext(), R.layout.question_item_rank, mDataList) {
            @Override
            protected void convert(ViewHolder holder, QuestionRankBean bean, int position) {
                RoundedImageView cover = holder.getView(R.id.cover);
                Glide.with(QuestionRankFragment.this)
                        .load(bean.getLogo())
                        .apply(new RequestOptions().placeholder(R.drawable.comment_head_default).placeholder(R.drawable.comment_head_default))
                        .into(cover);

                switch (position) {
                    case 0:
                        holder.setVisible(R.id.rank_cover, true);
                        holder.setTextColorRes(R.id.rank, R.color.question_rank_one);
                        holder.setImageResource(R.id.rank_cover, R.drawable.question_rank_one);
                        holder.setText(R.id.rank, "NO." + (position + 1));
                        break;
                    case 1:
                        holder.setVisible(R.id.rank_cover, true);
                        holder.setTextColorRes(R.id.rank, R.color.question_rank_two);
                        holder.setImageResource(R.id.rank_cover, R.drawable.question_rank_two);
                        holder.setText(R.id.rank, "NO." + (position + 1));
                        break;
                    case 2:
                        holder.setVisible(R.id.rank_cover, true);
                        holder.setTextColorRes(R.id.rank, R.color.question_rank_three);
                        holder.setImageResource(R.id.rank_cover, R.drawable.question_rank_three);
                        holder.setText(R.id.rank, "NO." + (position + 1));
                        break;
                    default:
                        holder.setVisible(R.id.rank_cover, false);
                        holder.setTextColorRes(R.id.rank, R.color.question_normal_color);
                        holder.setText(R.id.rank, (position + 1) + "");
                        break;
                }

                holder.setText(R.id.name, bean.getNickname());

                holder.setText(R.id.combo_num, bean.getBestNum() + "");

                holder.setText(R.id.times, bean.getTimes() + "");
            }
        });

        mPresenter.getList(subjectId, range, sort, lastPhoneNum, lastCorrectNum + "", lastTimes + "");

    }

    @Override
    protected void setListener() {
        sortRg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == -1) {
                    return;
                }
                if (checkedId == R.id.combo) {
                    sort = "correctNum";
                } else {
                    sort = "times";
                }

                lastPhoneNum = "";
                lastCorrectNum = 0;
                lastTimes = 0;

                mPresenter.getList(subjectId, range, sort, lastPhoneNum, lastCorrectNum + "", lastTimes + "");
            }
        });


        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                lastPhoneNum = "";
                lastCorrectNum = 0;
                lastTimes = 0;

                mPresenter.getList(subjectId, range, sort, lastPhoneNum, lastCorrectNum + "", lastTimes + "");
            }
        });

        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                lastPhoneNum = "";
                lastCorrectNum = 0;
                lastTimes = 0;

                mPresenter.getList(subjectId, range, sort, lastPhoneNum, lastCorrectNum + "", lastTimes + "");
            }
        });

        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPresenter.getList(subjectId, range, sort, lastPhoneNum, lastCorrectNum + "", lastTimes + "");
            }
        });
    }

    @Override
    protected void onFirstVisible() {

    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }

    @Override
    public void setList(List<QuestionRankBean> beanList, boolean isMore) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
        } else {
            refresh.finishRefresh();
            mDataList.clear();
        }
        lastPhoneNum = beanList.get(beanList.size() - 1).getUsername();
        if (sort.equals("correctNum")) {
            lastCorrectNum = beanList.get(beanList.size() - 1).getBestNum();
        } else {
            lastTimes = beanList.get(beanList.size() - 1).getTimes();
        }
        mDataList.addAll(beanList);
        commonAdapter.notifyDataSetChanged();
    }

    @Override
    public void setError(String msg, boolean isMore) {
        loadMask.setReloadButtonText("点击重试~");
        if (isMore) {
            refresh.finishLoadMore();
            if (!NetUtil.isNetworkAvalible(getContext())) {
                showToast("网络异常，请检查您的网络！", 4);
            }
        } else {
            refresh.finishRefresh();
            loadMask.setStatus(LoadingLayout.Error);
            if (!NetUtil.isNetworkAvalible(getContext())) {
                loadMask.setErrorImage(R.drawable.error_network);
                loadMask.setErrorText("网络异常，请检查您的网络！");
            } else if (msg.contains("暂无")) {
                loadMask.setErrorImage(R.drawable.empty_content);
                loadMask.setErrorText(msg);
            } else {
                loadMask.setErrorImage(R.drawable.error_content);
                loadMask.setErrorText(msg);
            }
        }
    }
}
